package com.booksystem.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.booksystem.common.RestResult;
import com.booksystem.dto.AddDeliveryDTO;
import com.booksystem.dto.ConfigShippingMethodDTO;
import com.booksystem.dto.QueryDeliveryDetailDTO;
import com.booksystem.dto.UpdateDeliveryStatusDTO;
import com.booksystem.entity.DeliveryInfo;
import com.booksystem.entity.OrderInfo;
import com.booksystem.entity.ShippingMethod;
import com.booksystem.mapper.DeliveryInfoMapper;
import com.booksystem.mapper.OrderInfoMapper;
import com.booksystem.mapper.ShippingMethodMapper;
import com.booksystem.service.DeliveryService;
import com.booksystem.utils.ResultCodeConstant;
import java.time.LocalDateTime;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 物流配送服务实现类
 * </p>
 * @author 段伟豪
 */
@Slf4j
@Service
public class DeliveryServiceImpl implements DeliveryService {

    @Autowired
    private DeliveryInfoMapper deliveryInfoMapper;

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private ShippingMethodMapper shippingMethodMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Boolean> addDelivery(AddDeliveryDTO addDeliveryDTO) {
        // 校验订单是否存在且状态允许发货
        QueryWrapper<OrderInfo> orderQuery = new QueryWrapper<>();
        orderQuery.select("order_status").eq("order_id", addDeliveryDTO.getOrderId());
        OrderInfo orderInfo = orderInfoMapper.selectOne(orderQuery);
        if (orderInfo == null || !isOrderAllowShipment(orderInfo.getOrderStatus())) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG, false);
        }

        // 将配送信息保存到数据库
        DeliveryInfo deliveryInfo = new DeliveryInfo();
        deliveryInfo.setOrderId(addDeliveryDTO.getOrderId());
        deliveryInfo.setTrackingNumber(addDeliveryDTO.getTrackingNumber());
        deliveryInfo.setExpressCompany(addDeliveryDTO.getExpressCompany());
        deliveryInfo.setDeliveryStatus(1); // 初始状态为已发货
        deliveryInfo.setDeliveryTime(LocalDateTime.now());
        int result = deliveryInfoMapper.insert(deliveryInfo);
        
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, result > 0);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Boolean> updateDeliveryStatus(UpdateDeliveryStatusDTO updateDeliveryStatusDTO) {
        // 判断配送信息是否存在
        DeliveryInfo deliveryInfo = deliveryInfoMapper.selectById(updateDeliveryStatusDTO.getDeliveryId());
        if (deliveryInfo == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG, false);
        }

        // 根据状态更新物流配送信息
        deliveryInfo.setDeliveryStatus(updateDeliveryStatusDTO.getDeliveryStatus());
        if (updateDeliveryStatusDTO.getDeliveryStatus() == 3) { // 已签收
            deliveryInfo.setSignTime(LocalDateTime.now());
        }
        int result = deliveryInfoMapper.updateById(deliveryInfo);
        
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, result > 0);
    }

    @Override
    public RestResult<DeliveryInfo> queryDeliveryDetail(QueryDeliveryDetailDTO queryDeliveryDetailDTO) {
        // 根据订单ID查找对应的配送信息
        DeliveryInfo deliveryInfo = deliveryInfoMapper.selectByOrderId(queryDeliveryDetailDTO.getOrderId());
        if (deliveryInfo == null) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG, null);
        }

        // 返回配送详情信息
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, deliveryInfo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResult<Boolean> configShippingMethod(ConfigShippingMethodDTO configShippingMethodDTO) {
        // 检查配送方式是否已存在
        if (shippingMethodMapper.existsByShippingMethod(configShippingMethodDTO.getShippingMethod())) {
            return new RestResult<>(ResultCodeConstant.CODE_000001, ResultCodeConstant.CODE_000001_MSG, false);
        }

        // 插入新的配送方式记录
        ShippingMethod shippingMethod = new ShippingMethod();
        shippingMethod.setShippingMethod(configShippingMethodDTO.getShippingMethod());
        shippingMethod.setDescription(configShippingMethodDTO.getDescription());
        shippingMethod.setCreateTime(LocalDateTime.now());
        int result = shippingMethodMapper.insert(shippingMethod);
        
        return new RestResult<>(ResultCodeConstant.CODE_000000, ResultCodeConstant.CODE_000000_MSG, result > 0);
    }

    /**
     * 判断订单是否允许发货
     *
     * @param status 订单状态
     * @return 是否允许发货
     */
    private boolean isOrderAllowShipment(Integer status) {
        return status != null && (status == 2 || status == 3); // 已付款或已发货状态可发货
    }
}